<?php

namespace App\Service;
use App\Common\Tools;
use App\Exception\BusinessException;
use App\Repository\ContactsRepo;
use App\Repository\GroupsRepo;
use App\Repository\UserRepo;

/**
 * 客户相关业务类
 *
 * @author WangBin
 */
class UserService extends Singleton
{
    const LOGIN_METHOD_PWD = 'PWD'; // 账户密码登录
    const LOGIN_METHOD_SMS = 'SMS'; // 短信验证码登录
    const LOGIN_METHOD_LIST = [
        self::LOGIN_METHOD_PWD,
    ];

    /**
     * 登录注册接口，不存在自动注册
     *
     * @param $params
     */
    public function login(array $params)
    {
        if(empty($params['login_method']) || !in_array($params['login_method'], self::LOGIN_METHOD_LIST)) {
            BusinessException::error(500, "不支持的登录场景");
        }
        $username = str_replace(" ", "", $params['username']);
        $password = str_replace(" ", "", $params['password']);
        if(empty($username) || empty($password)) {
            BusinessException::error(500, "用户名或密码为空");
        }
        if(strlen($password) < 6 || strlen($username) < 6) {
            BusinessException::error(500, "用户名或密码长度小于6位");
        }

        $user = UserRepo::getInstance()->getByLoginName($username);
        // 用户不存在自动注册账户、自动创建默认分组
        if(is_null($user)) {
            $secret = Tools::getUniqueId();
            $userId = UserRepo::getInstance()->save([
                'username' => Tools::makeNickname(),
                'login_name' => $username,
                'secret' => $secret,
                'password' => hash('sha256', $username . $secret),
            ]);
            if($userId == 0) {
                BusinessException::error(500, "自动注册出错");
            }
            $user = UserRepo::getInstance()->getById($userId);
            // 创建用户默认群组
            GroupsRepo::getInstance()->save(['group_name' => '未分组', 'user_id' => $userId, 'nickname' => $user->username, 'people_num' => 0]);
        }
        // 生成 token
        $token = JWTService::getInstance()->encode(['user_id' => $user->id, 'login_name' => $user->login_name, 'username' => $user->username]);
        if(empty($token)) {
            BusinessException::error(500, '登录失败');
        }
        return [
            'token' => $token,
            'expired_at' => config('jwt.expire') + time() - 60
        ];
    }

    /**
     * 聊天数据初始化
     *
     * @param array $params
     * @return array
     */
    public function init(array $params)
    {
        // 联系人信息
        $userInfo = UserRepo::getInstance()->getById($params['auto_user_id'], ['username', 'id', 'avatar', 'sign']);
        // 获取最近聊天联系人, 包含最新的一条消息
        $chatList = [];
        // 联系人列表
        $contactsList = ContactsRepo::getInstance()->getByUserId($params['auto_user_id'])->get();
        return ['userinfo' => $userInfo, 'chat_list' => $chatList, 'contacts' => $contactsList];
    }

    public function search(array $params)
    {
        if(empty($params['keywords'])) {
            BusinessException::error(500, "请输入搜索关键词");
        }
        $result = ContactsRepo::getInstance()->searchNewFriends($params);
        return $this->toList($result, $this->getPage($params['page']), $this->getPageSize($params['page_size']));
    }
}